package graduate.cslg.com.universityshopping;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import graduate.cslg.com.universityshopping.entity.UserBean;
import graduate.cslg.com.universityshopping.net.LoginResponse;
import graduate.cslg.com.universityshopping.net.RetrofitDevelop;
import graduate.cslg.com.universityshopping.utils.JellyInterpolator;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_login;
    TextView tv_register;
    private ObjectAnimator animator3;
    private View mInputLayout;
    private View progress;
    private ImageView iv_rotate;
    private ProgressBar pb_rotate;
    float mWidth, mHeight;
    private RelativeLayout userId;
    private RelativeLayout userPass;
    private EditText getId;
    private EditText getPass;
    private LoginResponse mLoginResponse;
    private UserBean mUserBean;
    private int userType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initViews();
    }

    private void initViews() {
        tv_login = findViewById(R.id.tv_login);
        progress = findViewById(R.id.layout_progress);
        iv_rotate = findViewById(R.id.iv_rotate);
        pb_rotate = findViewById(R.id.pb_rotate);
        mInputLayout = findViewById(R.id.input_layout);
        userId = findViewById(R.id.us_id);
        userPass = findViewById(R.id.us_pass);
        getId = findViewById(R.id.get_id);
        getPass = findViewById(R.id.get_pass);
        tv_register = findViewById(R.id.user_register);
        tv_login.setOnClickListener(this);
        tv_register.setOnClickListener(this);
    }

    /**
     * 入口
     * @param activity 进入主页的活动呢
     */
    public static void startAction(Activity activity){
        Intent intent = new Intent(activity, LoginActivity.class);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.fade_in,
                R.anim.fade_out);
    }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_login:
                    mWidth = tv_login.getMeasuredWidth();
                    mHeight = tv_login.getMeasuredHeight();
                    userId.setVisibility(View.INVISIBLE);
                    userPass.setVisibility(View.INVISIBLE);
                    tv_login.setVisibility(View.INVISIBLE);
                    inputAnimator(mWidth);
                    login(getId.getText().toString(), getPass.getText().toString());
                    break;
                case R.id.user_register:
                    startActivity(new Intent(this, RegisterActivity.class));
                    break;
            }
        }

    private void login(final String userAccount, String userPassword) {
        RetrofitDevelop.getTestService()
                .test_loginCheck(userAccount, userPassword)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginResponse>() {
                    @Override
                    public void onCompleted() {
                        if (mLoginResponse.getStatus().equals("true")) {
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            getUserName(userAccount);
                            SharedPreferences preferences = getSharedPreferences("user_info",MODE_PRIVATE);
                            //得到SharePreferences.Editor对象,并保存数据到该对象中
                            SharedPreferences.Editor editor = preferences.edit();
                            editor.putString("user_account", userAccount);
                            editor.putInt("user_type", userType);
                            //保存key-value对到文件中
                            editor.apply();
                            finish();
                        } else {
                            Toast.makeText(LoginActivity.this, "帐号或密码错误！", Toast.LENGTH_SHORT).show();
                            animator3.cancel();
                            inputAnimator();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(LoginActivity.this, "网络异常!", Toast.LENGTH_SHORT).show();
                        animator3.cancel();
                        inputAnimator();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(LoginResponse loginResponse) {
                        mLoginResponse = loginResponse;
                    }
                });
    }

    private void getUserName(String userAccount) {
        RetrofitDevelop.getTestService()
                .getUserName(userAccount)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UserBean>() {
                    @Override
                    public void onCompleted() {
                        userType = mUserBean.getUser_type();
                        SharedPreferences preferences = getSharedPreferences("user_info",MODE_PRIVATE);
                        //得到SharePreferences.Editor对象,并保存数据到该对象中
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putString("user_name", mUserBean.getUser_name());
                        editor.putString("user_phone", mUserBean.getUser_phone());
                        //保存key-value对到文件中
                        editor.apply();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(UserBean userBean) {
                        mUserBean = userBean;
                    }
                });
    }

    /**
     * 输入框放大的动画
     * */
    private void inputAnimator(){
        ObjectAnimator animator2 = ObjectAnimator.ofFloat(mInputLayout,
                "scaleX", 0.0f, 1f);
        animator2.setDuration(1000);
        animator2.start();
        animator2.addListener(new Animator.AnimatorListener() {

            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                tv_login.setVisibility(View.VISIBLE);
                tv_login.setEnabled(true);
                tv_login.setBackgroundResource(R.drawable.bg_login);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }
        });
    }

    /**
     * 输入框缩小的动画效果
     * @param w    宽
     */
    private void inputAnimator(float w) {
        AnimatorSet set = new AnimatorSet();

        ValueAnimator animator = ValueAnimator.ofFloat(0, w);

        ObjectAnimator animator2 = ObjectAnimator.ofFloat(mInputLayout,
                "scaleX", 1f, 0.0f);
        set.setDuration(1000);
        set.setInterpolator(new AccelerateDecelerateInterpolator());
        set.playTogether(animator, animator2);
        set.start();
        set.addListener(new Animator.AnimatorListener() {

            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                /*
                 * 动画结束后，先显示加载的动画，然后再隐藏输入框
                 */
                progress.setVisibility(View.VISIBLE);
                progressAnimator(progress);
                mInputLayout.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }
        });
    }

    /**
     * 出现进度动画
     *
     * @param view 视图
     */
    private void progressAnimator(final View view) {
        iv_rotate.setVisibility(View.GONE);
        pb_rotate.setVisibility(View.VISIBLE);
        PropertyValuesHolder animator = PropertyValuesHolder.ofFloat("scaleX",
                0.5f, 1f);
        PropertyValuesHolder animator2 = PropertyValuesHolder.ofFloat("scaleY",
                0.5f, 1f);
        animator3 = ObjectAnimator.ofPropertyValuesHolder(view,
                animator, animator2);
        animator3.setDuration(1000);
        animator3.setInterpolator(new JellyInterpolator());
        animator3.start();
    }
}
